package com.shelpe.services.sinbad.entity.jpa;

import java.util.Date;

import javax.persistence.AttributeConverter;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.Id;
import com.shelpe.services.sinbad.service.simbaproxy.UserClient;

import lombok.Data;

@Entity(name = "adgroup_targetings")
@Data
public class AdgroupTargeting {

	@Id
	@Column(name = "target_id")
	private long targetID;
	@Column(name = "user_id")
	private long userID;
	@Column(name = "campaign_id")
	private long campaignID;
	@Column(name = "crowd_name")
	private String crowdName;
	@Column(name = "adgroup_id")
	private long adgroupID;
	@Column(name = "price_mode")
	private int priceMode;

	private int discount;
	@Column(name = "online_status")
	@Convert(converter = StatusConverter.class)
	private Status onlineStatus;
	@Column(name = "is_default_price")
	private int isDefaultPrice;

	@Column(name = "create_time")
	private Date createTime;
	@Column(name = "updated_time")
	private Date updatedTime;

	public static enum Status {
		offline(0), online(1);

		private int value;

		private Status(int v) {
			this.value = v;
		}

		public int getValue() {
			return this.value;
		}

		public static Status from(int value) {
			Status en = Status.online;
			for (Status s : Status.values()) {
				if (s.getValue() == value) {
					en = s;
					break;
				}
			}
			return en;
		}
	}

	public static class StatusConverter implements AttributeConverter<Status, Integer> {

		@Override
		public Integer convertToDatabaseColumn(Status attribute) {
			return attribute != null ? attribute.getValue() : Status.offline.getValue();
		}

		@Override
		public Status convertToEntityAttribute(Integer dbData) {
			return Status.from(dbData);
		}
	}

	public void from(UserClient.SearchCrowdDto dto, Adgroup adgroup) {
		this.setAdgroupID(adgroup.getAutoID());
		this.setCampaignID(adgroup.getCampaignID());
		this.setUserID(adgroup.getUserID());
		this.setCreateTime(new Date());
		this.setUpdatedTime(new Date());
		this.setTargetID(dto.getTargetID());
		this.setPriceMode(dto.getPriceMode());
		this.setOnlineStatus(AdgroupTargeting.Status.from(dto.getOnlineStatus()));
		this.setDiscount(dto.getDiscount());
		this.setIsDefaultPrice(dto.getIsDefaultPrice());
		if (dto != null && dto.getCrowds() != null) {
			this.setCrowdName(dto.getCrowds().getName());
		}
	}
}
